package com.tianfeng.fenghuotoutiao.ui.activity;

import android.app.Activity;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tianfeng.fenghuotoutiao.R;
import com.tianfeng.fenghuotoutiao.model.bean.UserBean;
import com.tianfeng.fenghuotoutiao.net.api.ApiSMSSend;
import com.tianfeng.fenghuotoutiao.net.api.user.ApiShareSuccess;
import com.tianfeng.fenghuotoutiao.net.api.user.userInfo.ApiBindPhoneNumber;
import com.tianfeng.fenghuotoutiao.net.api.user.userInfo.ApiOnlyBindPhoneNumber;
import com.tianfeng.fenghuotoutiao.net.bean.ResEmpty;
import com.tianfeng.fenghuotoutiao.net.bean.news.ResAward;
import com.tianfeng.fenghuotoutiao.ui.activity.base.BaseActivity;
import com.tianfeng.fenghuotoutiao.ui.activity.other.LoginActivityOldNew;
import com.tianfeng.fenghuotoutiao.ui.activity.video.UserNowTixianStatus1Activity;
import com.tianfeng.fenghuotoutiao.ui.dialog.RedPacketDialog;
import com.tianfeng.fenghuotoutiao.utils.ButtonUtils;
import com.tianfeng.fenghuotoutiao.utils.GsonUtils;
import com.tianfeng.fenghuotoutiao.utils.SecurityUtils;
import com.tianfeng.fenghuotoutiao.utils.UIUtils;
import com.tianfeng.fenghuotoutiao.utils.Utils;
import com.tianfeng.fenghuotoutiao.utils.ValidUtils;
import com.tianfeng.fenghuotoutiao.wxapi.WXEntryActivity;
import com.zhxu.library.http.HttpManager;
import com.zhxu.library.listener.HttpOnNextListener;

import net.lucode.hackware.magicindicator.buildins.UIUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class UserNowTixianActivity extends BaseActivity {
    private static final String TYPE_WECHAT = "type_wechat";
    private static final String TYPE_WECHAT_MOMENT = "type_wechat_moment";

    private IWXAPI api;
    @Override
    protected void initView(View rootView, Bundle savedInstanceState) {
        UserBean userBean=getUserBean();
        isPhone(userBean.getUserid());
        lookmethod(userBean.getUserid());
        btn_commshare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (btn_commshare.getText().toString().equals("去分享")){
                    showShare("","","");
                }else{
                    Toast.makeText(UserNowTixianActivity.this, "当前任务完成了", Toast.LENGTH_SHORT).show();
                }
            }
        });
            ll_share.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (btn_commshare.getText().toString().equals("去分享")){
                    showShare("","","");
                    }else{
                        Toast.makeText(UserNowTixianActivity.this, "当前任务完成了", Toast.LENGTH_SHORT).show();
                    }
                }
            });




    }
     @BindView(R.id.btn_commshare)
    Button btn_commshare;
    @BindView(R.id.btn_bindphone)
    Button btn_bindphone;
    @BindView(R.id.btn_bindacc)
    Button btn_bindacc;
    @BindView(R.id.btn_gomethod)
    Button btn_gomethod;
    @BindView(R.id.ll_share)
    RelativeLayout ll_share;
    @BindView(R.id.ll_bindphone)
    RelativeLayout ll_bindphone;
    @BindView(R.id.ll_bind_acc)
    RelativeLayout ll_bind_acc;
    @OnClick(R.id.tv_back)
    public void onClickBack() {
        finish();
    }
    @OnClick({R.id.ll_bindphone,R.id.btn_bindphone})
    public void ll_bindphone() {
        if (btn_bindphone.getText().toString().equals("去绑定")) {
            doShowAddPhoneNumber();
        }else{
            Toast.makeText(this, "手机号已经绑定成功了", Toast.LENGTH_SHORT).show();
        }
    }
    @OnClick({R.id.ll_bind_acc,R.id.btn_bindacc})
    public void ll_bind_acc() {
        if (btn_bindacc.getText().toString().equals("未绑定")) {
            setmethod();
        }else {
            Toast.makeText(this, "提现方式已经设置完成", Toast.LENGTH_SHORT).show();
        }

    }
    @OnClick(R.id.btn_gomethod)
    public void btn_gomethod() {
       if (btn_commshare.getText().toString().equals("去分享")||btn_bindphone.getText().toString().equals("去绑定")||btn_bindacc.getText().toString().equals("去绑定")){
             toast("对不起，任务没有完成...");
       }else{
           UserBean userBean=getUserBean();
           gomethod(userBean.getUserid());
       }

    }

    /**
     * 分享朋友圈
     * @param title
     * @param shareContent
     * @param url
     */
    private void showShare(String title,String shareContent,String url) {
        WechatMoments.ShareParams sp = new WechatMoments.ShareParams();

        sp.setTitle("烽火头条");
        sp.setText("简单阅读,轻松赚零花钱");
        sp.setImageUrl("http://www.tianfengfeng168.com/ic_share.jpg");

        sp.setShareType(Platform.SHARE_IMAGE);
        Log.d("ShareSDK", sp.toMap().toString());
        Platform weChat = ShareSDK.getPlatform(WechatMoments.NAME);
        weChat.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
//                UIUtils.toast(UserNowTixianActivity.this,"分享成功");
       runOnUiThread(new Runnable() {
      @Override
      public void run() {
          btn_commshare.setText("已绑定");
          ll_share.setBackground(getResources().getDrawable(R.mipmap.ic_bind_wx_bg));
      }
  });
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                UIUtils.toast(UserNowTixianActivity.this,"分享错误");
            }

            @Override
            public void onCancel(Platform platform, int i) {
                UIUtils.toast(UserNowTixianActivity.this,"分享失败");
            }
        });

        weChat.share(sp);
    }


    @Override
    public int getContentLayout() {
        return R.layout.activity_user_now_tixian;
    }

    /**
     * bitmap 转换为字节数组
     */
    // 需要对图片进行处理，否则微信会在log中输出thumbData检查错误
    public static byte[] getBitmapBytes(Bitmap bitmap, boolean paramBoolean) {
        Bitmap localBitmap = Bitmap.createBitmap(80, 80, Bitmap.Config.RGB_565);
        Canvas localCanvas = new Canvas(localBitmap);
        int i;
        int j;
        if (bitmap.getHeight() > bitmap.getWidth()) {
            i = bitmap.getWidth();
            j = bitmap.getWidth();
        } else {
            i = bitmap.getHeight();
            j = bitmap.getHeight();
        }
        while (true) {
            localCanvas.drawBitmap(bitmap, new Rect(0, 0, i, j), new Rect(0, 0,
                    80, 80), null);
            if (paramBoolean)
                bitmap.recycle();
            ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream();
            localBitmap.compress(Bitmap.CompressFormat.JPEG, 100,
                    localByteArrayOutputStream);
            localBitmap.recycle();
            byte[] arrayOfByte = localByteArrayOutputStream.toByteArray();
            try {
                localByteArrayOutputStream.close();
                return arrayOfByte;
            } catch (Exception e) {
                // F.out(e);
            }
            i = bitmap.getHeight();
            j = bitmap.getHeight();
        }
    }

    private void doShowAddPhoneNumber() {

        final HashMap<String, String> paramsMap = new HashMap<>();
        AlertDialog.Builder builder= new AlertDialog.Builder(UserNowTixianActivity.this);
        builder.setTitle("绑定手机号");
        View view = View.inflate(UserNowTixianActivity.this, R.layout.dialog_bind_phone_number, null);

        final EditText mEtPhone = (EditText) view.findViewById(R.id.et_phone);
        final EditText mEtPhoneCode = (EditText) view.findViewById(R.id.et_phone_number_code);
        final TextView tvSendCode = (TextView) view.findViewById(R.id.tv_send_proof);
        tvSendCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String trim = mEtPhone.getText().toString().trim();
                if (!ValidUtils.isMobileNO(trim)) {
                    toast("请输入正确的手机号!");
                }

                //发送短信的一个方法；
                ApiSMSSend.defaultSend(UserNowTixianActivity.this, tvSendCode, trim, ApiSMSSend.BIND_PHONE_CODE);
            }
        });
        builder.setView(view);

        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        builder.setPositiveButton("确定", null);
        final AlertDialog alertDialog = builder.create();

        alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                //这里我们对进行一个验证的操作；

                Button button = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
                button.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View view) {
                        //这里我们对输入的内容进行一个校验操作；
                        String trim = mEtPhone.getText().toString().trim();
                        if (!ValidUtils.isMobileNO(trim)) {
                            toast("请输入正确的手机号!");
                            return;
                        }
                        String phoneCode = mEtPhoneCode.getText().toString().trim();
                        if (TextUtils.isEmpty(phoneCode)) {
                            toast("验证码不能为空!");
                            return;
                        }

                        paramsMap.put(ApiBindPhoneNumber.PHONE_NUMBER, trim);
                        paramsMap.put(ApiBindPhoneNumber.PHONE_CODE, phoneCode);
                        //这里实现绑定手机号的逻辑
                        bindPhoneNumber(paramsMap, alertDialog);
                    }
                });
            }
        });
        alertDialog.show();
    }


    /**
     * 这里要执行绑定手机号的逻辑；
     */
    private void bindPhoneNumber(HashMap<String, String> paramsMap, final AlertDialog alertDialog) {

        ApiOnlyBindPhoneNumber apiBindPhoneNumber = new ApiOnlyBindPhoneNumber(new HttpOnNextListener<ResEmpty>() {
            @Override
            public void onNext(ResEmpty userStr) {

                //这表示绑定成功；
                toast("手机号绑定成功！");
                if (btn_bindphone.getText().equals("已绑定")){
                    return;
                }else{
                    btn_bindphone.setText("已绑定");
                    ll_bindphone.setBackground(getResources().getDrawable(R.mipmap.ic_bind_wx_bg));
                }
                //这里是需要将绑定给移除的；
                alertDialog.dismiss();

            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                //这里表示绑定出错
                toast(e.getMessage());
//                if (btn_bindphone.getText().equals("已绑定")){
//                    return;
//                }else{
//                    btn_bindphone.setText("未绑定");
//                }
                alertDialog.dismiss();
            }
        }, UserNowTixianActivity.this, paramsMap);
        HttpManager.getInstance().doHttpDeal(apiBindPhoneNumber);
    }

    /**
     * 设置提现方式
     */
     public  void setmethod(){
         AlertDialog.Builder builder= new AlertDialog.Builder(UserNowTixianActivity.this);
         builder.setTitle("设置提现方式");
         View view = View.inflate(UserNowTixianActivity.this, R.layout.dialog_bind_method, null);

         final EditText mEtPhone = (EditText) view.findViewById(R.id.et_phone);
         final EditText mEtPhoneCode = (EditText) view.findViewById(R.id.et_phone_number_code);

         builder.setView(view);

         builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
             @Override
             public void onClick(DialogInterface dialog, int which) {
                 dismissDialog();
             }
         });
         builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
             @Override
             public void onClick(DialogInterface dialog, int which) {
                 UserBean userBean=getUserBean();
                 setAddmethod(userBean.getUserid(),phone,"1",mEtPhone.getText().toString(),mEtPhoneCode.getText().toString());
             }
         });

         builder.show();
     }


    /**
     * 查看是否绑定提现方式
     */
    String phone;
    public void isPhone(String str){
        OkHttpClient okHttpClient=new OkHttpClient();
        final Request request = new Request.Builder()
                .url("http://tianze1688.com/api/index.php/news/user/isPhone?osversion=7.1.2&sign=4524d2ddd1e6365daf499c914c425423&versionCode=18&adCode=18&timesc=1557912690304&phonemodel=xiaomi&phonetype=2&deviceid=864699035010366&channel=8&from_uid="+str)
                .get()//默认就是GET请求，可以不写
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                if (TextUtils.isEmpty(result)) return;
                JSONObject jsonObject= null;
                try {
                    jsonObject = new JSONObject(result);
                    String data=jsonObject.optString("data");
                    JSONObject jsonObject1=new JSONObject(data);
                     phone=jsonObject1.optString("phone");
                    if (TextUtils.isEmpty(phone)){
                         runOnUiThread(new Runnable() {
                             @Override
                             public void run() {
                                 btn_bindphone.setText("未绑定");
                             }
                         });

                    }else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                btn_bindphone.setText("已绑定");
                                ll_bindphone.setBackground(getResources().getDrawable(R.mipmap.ic_bind_wx_bg));
                            }
                        });

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }
    /**
     * 查看是否有提现方式
     */
    public void setAddmethod(String id,String phone,String type,String name,String accunt){
        OkHttpClient okHttpClient=new OkHttpClient();
        final Request request = new Request.Builder()
                .url("http://tianze1688.com/api/index.php/news/user/InserUser?osversion=7.1.2&sign=4524d2ddd1e6365daf499c914c425423&versionCode=18&adCode=18&timesc=1557912690304&phonemodel=xiaomi&phonetype=2&deviceid=864699035010366&channel=8" +
                        "&from_uid="+id+"&phone="+phone+"&type="+"1"+"&name="+name+"&accunt="+accunt)
                .get()//默认就是GET请求，可以不写
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                      runOnUiThread(new Runnable() {
                          @Override
                          public void run() {
                              btn_bindacc.setText("未绑定");
                          }
                      });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        toast("设置提现方式成功");
                        btn_bindacc.setText("已绑定");
                        ll_bind_acc.setBackground(getResources().getDrawable(R.mipmap.ic_bind_wx_bg));
                    }
                });



            }
        });
    }
    /**
     * 查看是否绑定提现方式
     */
    public void lookmethod(String id){
        OkHttpClient okHttpClient=new OkHttpClient();
        final Request request = new Request.Builder()
                .url("http://tianze1688.com/api/index.php/news/user/isaddmethod?osversion=7.1.2&sign=4524d2ddd1e6365daf499c914c425423&versionCode=18&adCode=18&timesc=1557912690304&phonemodel=xiaomi&phonetype=2&deviceid=864699035010366&channel=8&from_uid="+id)
                .get()//默认就是GET请求，可以不写
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                if (TextUtils.isEmpty(result)) return;
                JSONObject jsonObject= null;
                try {
                    jsonObject = new JSONObject(result);
                    String data=jsonObject.optString("data");

                    if (TextUtils.isEmpty(data)){
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                btn_bindacc.setText("未绑定");
                            }
                        });

                    }else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                btn_bindacc.setText("已绑定");
                                ll_bind_acc.setBackground(getResources().getDrawable(R.mipmap.ic_bind_wx_bg));
                            }
                        });

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    /**
     * 提现东西提交
     */
    public void gomethod(String id){
        OkHttpClient okHttpClient=new OkHttpClient();
        final Request request = new Request.Builder()
                .url("http://tianze1688.com/api/index.php/news/user/InserMethod?osversion=7.1.2&sign=4524d2ddd1e6365daf499c914c425423&versionCode=18&adCode=18&timesc=1557912690304&phonemodel=xiaomi&phonetype=2&deviceid=864699035010366&channel=8&from_uid="+id+"&status="+"0")
                .get()//默认就是GET请求，可以不写
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(UserNowTixianActivity.this, "提现数据正在上传....", Toast.LENGTH_SHORT).show();


                        finish();
                    }
                });


            }
        });
    }



}
